"""
数据库操作工具类
用法；
    db = mysqldb()
    # 查询：
    db.getOne(sql)
    db.getAll(sql)
    # 插入、删除或修改：
    db.query(sql)
"""
import pymysql
from app.config import Config


class mysqldb:
    db_conn = None
    db_cursor = None
    db_where = []
    db_fields = []

    def __init__(self):
        self.db_conn = pymysql.connect(**Config.get_mysql_options())

    def __del__(self):
        if self.db_conn != None:
            self.db_conn.close()
            self.db_conn = None

    def close(self):
        if self.db_conn != None:
            self.db_conn.close()
            self.db_conn = None
        # print("close db")

    def getAll(self, sql):
        if self.db_conn != None:
            cursor = self.db_conn.cursor(cursor=pymysql.cursors.DictCursor)
            cursor.execute(sql)
            return cursor.fetchall()
        return []

    def getOne(self, sql):
        if self.db_conn != None:
            cursor = self.db_conn.cursor(cursor=pymysql.cursors.DictCursor)
            cursor.execute(sql)
            return cursor.fetchone()
        return []

    def query(self, sql):
        if self.db_conn != None:
            cursor = self.db_conn.cursor()
            r = cursor.execute(sql)
            self.db_conn.commit()
            return r
        return False


def get_db():
    """
    获取数据库对象，用完自动关闭
        用于在fastapi已依赖注入方式引入
        db=Depends(get_db)
    :return:
    """
    db = mysqldb()
    try:
        yield db
    finally:
        db.close()
